package com.com.typhoon.dao;

import com.com.typhoon.entity.Permission;
import com.com.typhoon.entity.Role;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author shuya | dongfeng.zdf@alibaba-inc.com
 * @description
 * @date 2018/10/30 上午10:38
 * @description
 * @modified by
 * @since V2.0.0
 */
@Repository
@Slf4j
public class PermissionDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<Permission> queryPermissionByRoles(List<Long> roleIds) {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("select p.*,rop.roleId as roleId from Permission p left join RoleOfPermission rop on p.id = rop.permissionId where rop.roleId in (");
        for(int i = 0,size = roleIds.size();i  < size ;i ++) {
            sqlBuilder.append(roleIds.get(i));
            if(i < size - 1) {
                sqlBuilder.append(",");
            }
        }
        sqlBuilder.append(")");
        log.info("query pemission sql={}",sqlBuilder.toString());
        List<Permission> permissionList = this.jdbcTemplate.query(sqlBuilder.toString(), BeanPropertyRowMapper.newInstance(Permission.class));
        if(null == permissionList || permissionList.isEmpty()) {
            return Collections.emptyList();
        }
        return permissionList;
    }


}
